package com.mvc.core.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.SerializationUtils;
import org.springframework.stereotype.Component;

/**
 * @author 李涛
 * @version 创建时间：2018年8月31日 下午2:36:48 类说明
 */
@Aspect
@Component
public class MongoLog {

	private static Logger logger = LoggerFactory.getLogger(MongoLog.class);

	/**
	 * 拦截mongodb的执行nosql方法
	 */
	@Pointcut("execution(* org.springframework.data.mongodb.core.MongoOperations+.*(..))")
	public void pointCut() {
	}

	@Before("pointCut()")
	public void excuteQuery(JoinPoint joinPoint) throws Throwable {
		Object[] args = joinPoint.getArgs();
		if (args.length == 0) {
			return;
		}
		// 查询参数
		Query query = null;
		String table = null;
		for (int i = 0; i < args.length; i++) {
			Object arg = args[i];
			if (arg instanceof Class) {
				Class<?> cls = (Class<?>) arg;
				table = cls.getSimpleName();
			}
			if (arg.getClass() == Query.class) {
				// 查询参数
				query = (Query) arg;
			}
		}
		if (null != query && table != null) {
			if (logger.isDebugEnabled()) {
				logger.debug("[" + table + "]:" + SerializationUtils.serializeToJsonSafely(query.getQueryObject()));
			}
		}
	}
}
